package com.kimoge.spring6.aop.annotationaop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author kimoge
 * @date 2025/8/28
 * @description 创建日志切面类
 */
@Aspect
@Component
// 多个切面类时，决定不同切面的优先级，值越小优先级越高
@Order(1)
public class LogAspect {
    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        System.out.println("Logger=>前置通知，方法名：" + joinPoint.getSignature().getName()+"，参数："+ Arrays.toString(args));
    }

    @AfterReturning(value = "execution(* com.kimoge.spring6.aop.annotationaop.CalculatorImpl.*(..))", returning = "result")
    public void afterMethod(JoinPoint joinPoint, Object result) {
        System.out.println("Logger=>返回通知，方法名：" + joinPoint.getSignature().getName()+"，返回结果："+result);
    }

    @After(value = "execution(* com.kimoge.spring6.aop.annotationaop.CalculatorImpl.*(..))")
    public void after(JoinPoint joinPoint) {
        System.out.println("Logger=>后置通知，方法名：" + joinPoint.getSignature().getName()+"，方法执行结束");
    }

    @AfterThrowing(value = "execution(* com.kimoge.spring6.aop.annotationaop.CalculatorImpl.*(..))", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Exception ex) {
        System.out.println("Logger=>后置通知，方法名：" + joinPoint.getSignature().getName()+",错误："+ex.getMessage());
    }

    @Around("execution(* com.kimoge.spring6.aop.annotationaop.CalculatorImpl.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        String string = Arrays.toString(joinPoint.getArgs());
        Object result = null;
        try {
            System.out.println("Logger=>环绕通知，方法名：" + joinPoint.getSignature().getName()+"，参数："+string);
            // 目标方法的执行
            result = joinPoint.proceed();
            System.out.println("Logger=>环绕通知，方法名：" + joinPoint.getSignature().getName()+"，结果："+result);
        } catch (Throwable e) {
            System.out.println("Logger=>环绕通知，方法名：" + joinPoint.getSignature().getName()+"，错误："+e.getMessage());
        } finally {
            System.out.println("Logger=>环绕通知，方法名：" + joinPoint.getSignature().getName()+"，方法执行结束");
        }
        return result;
    }

    // 重用切入点表达式
    @Pointcut("execution(* com.kimoge.spring6.aop.annotationaop.CalculatorImpl.*(..))")
    public void pointCut() {}
}
